<script setup lang="ts">
import { ref, computed, watchEffect } from 'vue'
import { MoreHorizontalIcon } from 'lucide-vue-next'
import { Handle, Position, useVueFlow, useNode } from '@vue-flow/core'
import { Input } from '@/components/ui/input'
import { Menubar, MenubarMenu, MenubarTrigger, MenubarContent, MenubarItem } from '@/components/ui/menubar'
import { Tabs, TabsTrigger, TabsContent, TabsList } from '@/components/ui/tabs'
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from '@/components/ui/tooltip'
import { Collapsible, CollapsibleTrigger, CollapsibleContent } from '@/components/ui/collapsible'
import CommonBasicModule from '../common-basic-module.vue'
import CommonPromptModule from '../common-prompt-module.vue'
import commonOutputModule from '../common-output-module.vue'
import { ChevronsUpDownIcon, ChevronDown, ChevronUp, PlusIcon, AlertCircleIcon, MinusCircleIcon } from 'lucide-vue-next'
import CommonNextNodeForm from '@/components/vue-flow/common-next-node-form.vue'
import { findConnectNodeByTarget } from '@/lib/vueFlowUtils'
import { LLMNodeData, LLMNodeEvents } from './index'
import SelectComponent from '@/components/vue-flow/nodes/selectComponent.vue'
import storeMap from '@/pina/index'
import commonBasicFormVue from '@/components/vue-flow/common-basic-form.vue'
import { LLMOptions } from '@/lib/dict'
// import type { NodeProps,EdgeProps } from '@vue-flow/core'
import {
  Select,
  SelectContent,
  SelectGroup,
  SelectItem,
  SelectTrigger,
  SelectValue,
  SelectItemText
} from '@/components/ui/select'
import { Textarea } from '@/components/ui/textarea'
import { useLLMStore } from '@/pina/LLMStore'
defineOptions({
  components: {
    Menubar,
    MenubarMenu,
    MenubarTrigger,
    MenubarContent,
    MenubarItem,
    Tabs,
    TabsTrigger,
    TabsContent,
    TabsList,
    Tooltip,
    TooltipContent,
    TooltipProvider,
    TooltipTrigger,
    Collapsible,
    CollapsibleTrigger,
    CollapsibleContent,
    ChevronsUpDownIcon,
    ChevronDown,
    ChevronUp,
    PlusIcon,
    AlertCircleIcon,
    MinusCircleIcon,
    Select,
    SelectContent,
    SelectGroup,
    SelectItem,
    SelectTrigger,
    SelectValue,
    SelectItemText,
    CommonBasicModule,
    CommonPromptModule,
    commonOutputModule,
    CommonNextNodeForm,
    Textarea,
    commonBasicFormVue,
    SelectComponent
  }
})
const isOpen = ref(true)
const isEditTitle = ref(false)
const prevNodeId = ref<string | undefined>()
const node = useNode()

const { removeNodes, nodes, addNodes, edges, findNode } = useVueFlow()
function handleClickDeleteBtn() {
  removeNodes(node.id)
}
function handleClickDuplicateBtn() {
  const { type, position, label, data } = node.node
  const newNode = {
    id: (nodes.value.length + 1).toString(),
    type,
    position: {
      x: position.x + 100,
      y: position.y + 100
    },
    label,
    data
  }
  addNodes(newNode)
}
const LLM = storeMap.useLLMStore()
const LLMData = computed(() => {
  LLM.template.data.input.forEach((item: any, index: number) => {
    item.action = index
  })
  return LLM.template.data
})
const DLSData = LLM.template.data
const handleClickAddBtn = () => {
  LLM.add()
  // saveData()
}
const handleClickOutPutAddBtn = () => {
  LLM.outputadd()
  // LLMoutput.add()
  // saveData()
}
const saveData = () => {
  node.node.data = {
    //给node节点添加到json当中
    id: LLM.template.id,
    type: LLM.template.type,
    ...LLMData.value
  }
}
watchEffect(() => {
  if (node.connectedEdges && node.connectedEdges.value.length > 0) {
    saveData()
  }
  const edgeObject =  node.connectedEdges.value.find(item=>item.target==node.id)
  if(!edgeObject){
    LLM.clearData()
  }
})
const handleEdietTitle =()=>{
  isEditTitle.value = false;
  storeMap.useOptionsStore().changeTitle = DLSData.title
}
const handleMousedown=(event)=> {
      // 阻止textarea区域内触发节点拖拽事件
      event.stopPropagation();
    }
const handleMouseup=(event)=>{
      // 鼠标抬起时也阻止节点的拖拽事件
      event.stopPropagation();
    }
</script>

<template>
  <div class="rounded-sm border-gray-200 bg-white p-3 shadow-md">
    <Handle type="target" :position="Position.Left" />
    <div class="flex flex-col gap-y-4">
      <div class="flex justify-between">
        <div class="flex gap-x-2">
          <img src="~@/assets/images/icon_LLM.png" class="mt-1 h-4 w-4" alt="LLM icon" />
          <div class="flex flex-col gap-y-1">
            <Input v-model="DLSData.title" class="h-5" v-if="isEditTitle" @blur="handleEdietTitle" />
            <h3 class="text-base" v-else>{{ DLSData.title }}</h3>
            <p class="ml-[-25px] text-sm text-gray-500">调用大型语言模型，使用变量和提示词生成响应。</p>
          </div>
        </div>

        <Menubar class="border-none">
          <menubar-menu>
            <menubar-trigger>
              <more-horizontal-icon />
            </menubar-trigger>
            <menubar-content>
              <menubar-item @click="handleClickDuplicateBtn"> 复制 </menubar-item>
              <menubar-item @click="handleClickDeleteBtn"> 删除 </menubar-item>
              <menubar-item @click="isEditTitle = true"> 重命名 </menubar-item>
            </menubar-content>
          </menubar-menu>
        </Menubar>
      </div>
      <div class="grid gap-y-3">
        <div class="rounded-md bg-muted p-4">
          <Collapsible v-model:open="isOpen">
            <collapsible-trigger as-child>
              <div class="flex w-full items-center justify-between">
                <div class="flex items-center gap-x-2">
                  <component :is="isOpen ? ChevronDown : ChevronUp" class="h-4 w-4 cursor-pointer" />
                  <p>模型</p>
                  <tooltip-provider>
                    <tooltip>
                      <tooltip-trigger>
                        <alert-circle-icon class="h-3 w-3 text-muted-foreground" />
                      </tooltip-trigger>
                      <tooltip-content>
                        <p class="max-w-60">
                          <!-- {{description}} -->
                          编辑大模型的提示词以生成内容
                        </p>
                      </tooltip-content>
                    </tooltip>
                  </tooltip-provider>
                </div>
              </div>
            </collapsible-trigger>
            <collapsible-content class="space-y-3 px-3 py-3">
              <div class="formBox">
                <Select v-model="LLMData.llm.name">
                  <SelectTrigger class="w-full" as="div">
                    <SelectValue placeholder="请选择类型" />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectGroup>
                      <SelectItem v-for="(item, index) in LLMOptions" :key="index" :value="item.value">
                        {{ item.label }}
                      </SelectItem>
                    </SelectGroup>
                  </SelectContent>
                </Select>
              </div>
            </collapsible-content>
          </Collapsible>
        </div>
        <div class="mt-1 rounded-md bg-muted p-4">
          <Common-next-node-form :DLSData="LLMData" @onClickAddBtn="handleClickAddBtn" storeId="useLLMStore">
          </Common-next-node-form>
        </div>
        <div class="mt-1 rounded-md bg-muted p-4">
          <Collapsible v-model:open="isOpen">
            <collapsible-trigger as-child>
              <div class="flex w-full items-center justify-between">
                <div class="flex items-center gap-x-2">
                  <component :is="isOpen ? ChevronDown : ChevronUp" class="h-4 w-4 cursor-pointer" />
                  <p>提示词</p>
                  <tooltip-provider>
                    <tooltip>
                      <tooltip-trigger>
                        <alert-circle-icon class="h-3 w-3 text-muted-foreground" />
                      </tooltip-trigger>
                      <tooltip-content>
                        <p class="max-w-60">
                          <!-- {{description}} -->
                          编辑大模型的提示词以生成内容
                        </p>
                      </tooltip-content>
                    </tooltip>
                  </tooltip-provider>
                </div>
              </div>
            </collapsible-trigger>
            <collapsible-content class="space-y-3 px-3 py-3">
              <div class="formBox">
                <Textarea v-model="DLSData.prompt" @mousedown.stop="handleMousedown"
                @mouseup.stop="handleMouseup" @change.stop="saveData" class="font-12 h-24 w-full p-2" :placeholder="DLSData.placeholder" />
              </div>
            </collapsible-content>
          </Collapsible>
        </div>
        <div class="mt-1 rounded-md bg-muted p-4">
          <common-basic-form-vue
            :DLSData="LLMData"
            @onClickAddBtn="handleClickOutPutAddBtn"
            :nodeType="LLM.template.type"
            storeId="useLLMStore"
            title="输出"
          >
          </common-basic-form-vue>
        </div>
      </div>
    </div>
    <Handle type="source" :position="Position.Right" />
  </div>
</template>
